
package com.lwl.java8.chapter8;

import com.lwl.java8.chapter8.chain.HeaderTextProcessing;
import com.lwl.java8.chapter8.chain.ProcessingObject;
import com.lwl.java8.chapter8.chain.SpellCheckerProcessing;
import com.lwl.java8.chapter8.observer.Feed;
import com.lwl.java8.chapter8.observer.Guardian;
import com.lwl.java8.chapter8.observer.LeMonde;
import com.lwl.java8.chapter8.observer.NYTimes;
import com.lwl.java8.chapter8.strategy.IsAllLowerCase;
import com.lwl.java8.chapter8.strategy.IsNumeric;
import com.lwl.java8.chapter8.strategy.ValidationStrategy;
import com.lwl.java8.chapter8.template.OnlineBanking;
import com.lwl.java8.chapter8.template.OnlineBankingLambda;
import org.junit.Test;

import java.util.function.Function;
import java.util.function.UnaryOperator;

public class Chapter8 {

	/**
	 * 策略模式测试
	 */
	@Test
	public void strategyTest() {

		long start = System.nanoTime();
		ValidationStrategy validation;
		validation = new IsAllLowerCase();
		System.out.println(validation.execute("sada"));
		validation = new IsNumeric();
		System.out.println(validation.execute("4l"));

		ValidationStrategy allLower = (strnum) -> strnum.matches("[a-z]+");
		System.out.println(allLower.execute("hahaahahA"));

		ValidationStrategy allNum = (strnum) -> strnum.matches("\\d+");
		System.out.println(allNum.execute("111"));
		System.out.println(System.nanoTime() - start);
	}

	/**
	 * 模板方法测试
	 */
	@Test
	public void templateTest() {

		OnlineBanking onlineBanking = new OnlineBankingLambda();
		onlineBanking.processCustomer(1);

		onlineBanking.processCustomer(2, (customer) -> System.out.println(customer));

		onlineBanking.processCustomer(3, System.out::println);
	}

	/**
	 * 观察者模式
	 */
	@Test
	public void observer() {

		Feed f = new Feed();
		f.registerObserver(new NYTimes());
		f.registerObserver(new Guardian());
		f.registerObserver(new LeMonde());
		f.registerObserver((String tweet) -> {
			if (tweet != null && tweet.contains("money")) {
				System.out.println("Breaking news in NY! " + tweet);
			}
		});
		f.notifyObservers("The queen said her favourite book is Java 8 in Action!");
	}

	@Test
	public void chainTest() {
		ProcessingObject<String> p1 = new HeaderTextProcessing();
		ProcessingObject<String> p2 = new SpellCheckerProcessing();
		p1.doThen(p2);
		String result = p1.handle("Aren't labdas really sexy?!!");
		System.out.println(result);

		UnaryOperator<String> headerProcessing = (String text) -> "From Raoul, Mario and Alan: " + text;
		UnaryOperator<String> spellCheckerProcessing = (String text) -> text.replaceAll("labda", "lambda");
		Function<String, String> pipeline = headerProcessing.andThen(spellCheckerProcessing);
		String result2 = pipeline.apply("Aren't labdas really sexy?!!");
		System.out.println(result2);

	}

}
